# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(plyr)
library(gridExtra)
library(scales)
library(egg)
library(optparse)
library(grid)
library(cowplot)
library(tidyverse)

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

option_list <- list(
make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
    select(c("SampleID", "ClassNote")) %>%
    mutate(ClassNote = as.character(ClassNote)) %>%
    mutate(ClassNote = factor(ClassNote, levels = unique(ClassNote)))

sampleColDf <- read.csv(opt$sc, header = T, stringsAsFactors = F, comment.char = "") %>%
select(c("ClassNote", "col"))
sampleCols <- sampleColDf %>%
deframe()

classNotes <- unique(sampleInfo$ClassNote)

diffData <- read_csv("Markers.csv")

if (nrow(diffData) == 0) {
    quit(status = 0)
}

diffNames <- diffData %>%
.$Metabolite

parent <- "./"
fileName <- paste0(parent, "/../uni/AllMet_Test.csv")
outFileName <- paste0(parent, "/Markers_Boxplot.pdf")
pValueData <- read.csv(fileName, header = T, stringsAsFactors = F, comment.char = "") %>%
    filter(Metabolite %in% diffNames) %>%
    arrange(P)
names <- pValueData$Metabolite
data <- read.csv(opt$i, header = T, stringsAsFactors = FALSE) %>%
    select(- c("HMDB", "KEGG", "Class")) %>%
    gather("SampleID", "Value", - Metabolite) %>%
    inner_join(sampleInfo, by = c("SampleID"))
getP <- function(name){
    pData <- data %>% filter(Metabolite == name)
    pValueDf <- pValueData %>% filter(Metabolite == name)
    p <- ggplot(pData, mapping = aes(x = ClassNote, y = Value, fill = ClassNote)) +
        theme_bw(base_size = 8, base_family = "Times") +
        theme(axis.text.x = element_text(size = 8, vjust = 0.5),
        axis.text.y = element_text(size = 8), legend.position = 'none',
        axis.title.y = element_text(size = 11), legend.margin = margin(t = 0.3, b = 0.1, unit = 'cm'),
        legend.text = element_text(size = 6), axis.title.x = element_text(size = 11), panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(), plot.title = element_text(hjust = 0.5, size = 8),
        panel.border = element_rect(size = 0.25)
        ) +
        xlab("") +
        ylab("") +
        ggtitle(paste0(pValueDf$Metabolite, "\n", "P=", scientific(pValueDf$P, 2))) +
        scale_fill_manual("", values = sampleCols) +
        stat_boxplot(geom = "errorbar", width = 0.5) +
        geom_boxplot(outlier.size = 0.75)
    return(p)
}

p <- names %>%
map(getP)

pdf(outFileName, 7.5, 9)
for (i in seq(1, length(p), 9)) {
    plot.new()
    iEnd <- i + 8
    inP <- p[i : iEnd] %>%
    map(function(x){
        if (is.null(x)) {
            p <- ggplot() + theme_void()
            p
        }else x
    })
    inEnd <- if (length(inP) < 3) {
        length(inP)
    }else 3
    inP[1 : inEnd] = inP[1 : inEnd] %>%
    map(~ .x + theme(plot.margin = margin(t = 0.5, unit = "cm")))
    ggarrange(plots = inP, ncol = 3, newpage = F)
}
dev.off()








